const modal = document.getElementById('modal');
const modalBody = document.getElementById('modalBody');
const closeModal = document.getElementById('closeModal');
let questionNum = 0;
// 初始化
document.addEventListener('DOMContentLoaded', () => {
    closeModal.addEventListener('click', () => {modal.style.display = 'none';console.log('Modal closed')});
});

async function generateQuestion() {
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'loading';
    loadingDiv.innerText = '生成中请稍后'; // 初始化为空
    document.getElementById('content').appendChild(loadingDiv);
    const res = await fetch('/api/generate/question', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('token') || ''}`,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            'questionNum': questionNum
        })
    });
    

    if (!res.ok) throw new Error('试题生成失败');

    // 一次性获取完整 JSON
    const data = await res.json();
    console.log('Received question data:', data);
    try{
        console.log(data.question.trim());
        const questionData = parseQuestionData(data.question.trim());
        renderQuestionBlock(questionData);
    }catch(err){
        alert("题目解析失败");
        const container = document.getElementById('content');
        const div = document.createElement('div');
        div.className = 'question-box';
        div.textContent = JSON.stringify(data, null, 2);
        container.append(div);
        container.append(document.createElement("hr"));
    }
    questionNum += 1; // 更新题目编号
}


async function generateListening() {
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'loading';
    loadingDiv.innerText = '正在生成音频，请稍后'; // 初始化为空
    document.getElementById('content').appendChild(loadingDiv);
    try {
    const res = await fetch('/api/generate/listening',{
        method: 'GET',
        headers: {
            
        }
    });
    if (!res.ok) throw new Error('听力生成失败');
    const blob = await res.blob();

    const audioURL = URL.createObjectURL(blob);
    const audio = document.createElement('audio');
    audio.controls = true;
    audio.src = audioURL;

    document.getElementById('content').appendChild(audio);
    document.getElementById('content').appendChild(document.createElement("hr"));
    } catch (err) {
        alert('生成听力出错: ' + err.message);
    }
}

function parseQuestionData(raw) {
    // --- 1. 从原始文本中提取第一个完整的 JSON 对象 ---
    let start = raw.indexOf('{');
    if (start === -1) return null;

    let depth = 0;
    let end = -1;
    for (let i = start; i < raw.length; i++) {
        if (raw[i] === '{') depth++;
        else if (raw[i] === '}') {
            depth--;
            if (depth === 0) {
                end = i;
                break;
            }
        }
    }
    if (end === -1) return null;

    let jsonStr = raw.slice(start, end + 1);

    // --- 2. 处理单引号和双花括号 ---
    // 替换单引号为双引号（JSON 要求双引号）
    // jsonStr = jsonStr.replace(/'/g, '"');
    
    // // 处理双花括号格式（将 {{...}} 转换为 {...}）
    // if (jsonStr.startsWith('{{') && jsonStr.endsWith('}}')) {
    //     jsonStr = jsonStr.slice(1, -1);
    // }

    // --- 3. 尝试 JSON 解析 ---
    try {
        const obj = JSON.parse(jsonStr);
        
        // 处理新格式：{'title':..., 'options':{'A':..., 'B':...}, 'answer':...}
        if (obj.options && typeof obj.options === 'object') {
            // 将选项对象转换为选项数组（保持顺序 A, B, C...）
            const optionsArray = [];
            for (const key of ['A', 'B', 'C', 'D']) {
                if (obj.options[key]) {
                    optionsArray.push(obj.options[key]);
                }
            }
            
            return {
                question: obj.title,
                options: optionsArray,
                answer: obj.answer
            };
        }
        
        // 处理旧格式
        return {
            question: obj.title,
            options: Object.values(obj.options),
            answer: obj.answer
        };
    } catch (e) {
        console.error("JSON 解析失败", e);
    }

    return null;
}

function renderQuestionBlock({ question, options, answer }) {
    const container = document.getElementById('content');
    const div = document.createElement('div');
    div.className = 'question-box';

    const title = document.createElement('p');
    title.textContent = question;
    div.appendChild(title);

    const form = document.createElement('form');
    const optionLetters = ['A', 'B', 'C', 'D'];
    
    // 存储单选按钮的引用
    const radioButtons = [];
    
    options.forEach((opt, index) => {
        const label = document.createElement('label');
        label.className = 'option';

        const input = document.createElement('input');
        input.type = 'radio';
        input.name = 'choice';
        input.value = optionLetters[index]; // 使用选项字母（A, B, C...）
        radioButtons.push(input); // 保存引用

        label.appendChild(input);
        label.appendChild(document.createTextNode(optionLetters[index] + '. ' + opt));
        form.appendChild(label);
        form.appendChild(document.createElement('br'));
    });

    const submitBtn = document.createElement('button');
    submitBtn.type = 'button';
    submitBtn.textContent = '提交';

    const feedback = document.createElement('div');
    feedback.style.marginTop = '10px';

    submitBtn.addEventListener('click', () => {
        const selected = form.querySelector('input[name="choice"]:checked');
        if (!selected) {
            feedback.textContent = '❗ 请选择一个选项';
            feedback.style.color = 'red';
            return;
        }

        // 禁用所有单选按钮和提交按钮
        radioButtons.forEach(radio => {
            radio.disabled = true;
        });
        submitBtn.disabled = true;
        
        if (selected.value === answer) {
            feedback.textContent = '✅ 回答正确！';
            feedback.style.color = 'green';
        } else {
            feedback.textContent = `❌ 回答错误，正确答案是 ${answer}`;
            feedback.style.color = 'red';
        }
    });

    div.appendChild(form);
    div.appendChild(submitBtn);
    div.appendChild(feedback);
    container.appendChild(div);
    container.appendChild(document.createElement("hr"));
}